import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
import { resolve } from 'path'
import postCssPxToRem from 'postcss-pxtorem'
const _Config = require('./config/index')


// https://vitejs.dev/config/
export default ({ mode }) => {
  console.log(mode , '----BASE_mode')
  const env = loadEnv(mode, process.cwd());
  return defineConfig({
    base: _Config.BASE_URL[mode],
    // base: env.VITE_APP_BASE_URL,
    define: {
      'process.env': process.env
    },
    server: {
      proxy: _Config.proxy
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 39, 
            propList: ['*'], 
          })
        ]
      }
    },
    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver()],
      }),
      createHtmlPlugin({
        minify: true,
        // entry: 'src/main.ts',
        template: 'public/index.html',
        inject: {
          data: {
            title: _Config.BASE_TITLE,
            icon: _Config.BASE_ICON,
            injectScript: _Config.BASE_INJECT,
          },
        },
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, './src')
      }
    },
    build: {
      target: 'es2015',
      assetsInlineLimit: 10240,
      cssCodeSplit: false,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        }
      },
      rollupOptions: {
        output: {
          chunkFileNames: `static/js/[name].${_Config.BASE_HASH}.js`,
          entryFileNames: `static/js/[name].${_Config.BASE_HASH}.js`,
          assetFileNames: `static/[ext]/[name].${_Config.BASE_HASH}.[ext]`,
          manualChunks(id) {
            if(id.includes('src')) {
              return 'build'
            } else if(id.includes('node_modules')) {
              return 'vendor'
            } 
          }
        }
      }
    }
  })
}
